package com.lagou.service.impl;

import com.lagou.mapper.LoginMapper;
import com.lagou.mapper.UserMapper;
import com.lagou.pojo.Login;
import com.lagou.pojo.User;
import com.lagou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public boolean registerUser(String email, String password, String code) {

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        log.info("registerUser end");
        return userMapper.registerUser(user);
    }

    @Override
    public boolean isRegistered(String email) {
        String s = userMapper.isRegistered(email);
        if(StringUtils.isEmpty(s)){
            return true;
        }

        if("1".equals(s)){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public String login(String email, String password) {
        //使用uuid模拟生成token

        String token = UUID.randomUUID().toString().substring(0, 8);
        User user = new User();
        user.setEmail(email);
        log.info("token : " + token);
        //查询userid
        int userId = userMapper.queryUserId(email);
        Login login = new Login();
        login.setUserId(userId);
        login.setToken(token);
        loginMapper.saveToken(login);

        return token;
    }

    @Override
    public String getEmail(String token) {
        //根据token获取email
        //1.根据token获取userid
        int userId = loginMapper.queryUserIdByToken(token);
        if(userId == 0){
            return "未知的email";
        }
        String email = userMapper.queryEmailByUserId(userId);
        if(StringUtils.isEmpty(email)){
            return "未知的email";
        }
        return email;
    }
}
